package com.tledu.springboot04.service;

import com.tledu.springboot04.domain.Resources;
import com.tledu.springboot04.mapper.ResourcesMapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Antg
 * @date 2021/8/26  19:53
 */
@Service
@AllArgsConstructor
public class ResourcesServiceImpl implements ResourcesService {
    private final ResourcesMapper resourcesMapper;

    @Override
    public List<Resources> list() {
        List<Resources> list = resourcesMapper.list();
        Map<Integer, Resources> map = new HashMap<>();
        list.forEach(res -> map.put(res.getId(), res));
        List<Resources> treeList = new ArrayList<>();
        for (Resources resources : list) {
            //首先从map中查找是否有该父节点,没有的话就是根节点,直接添加到treeList中
            if (!map.containsKey(resources.getParentId())) {
                treeList.add(resources);
            } else {
                //找到了说明是个子节点,那么就将它加入到父节点的子节点list中
                map.get(resources.getParentId()).getChildrenList().add(resources);
            }
        }
        return treeList;
    }
}
